<template>
    <!-- start表单主体部分 -->
    <el-row>
        <el-col :span="24">
            <el-card style="max-width: 100%">
                <el-button type="success" style="margin: 8px;" @click="AddShowFlag = true">添加</el-button>
                <!--父分类筛选器-->
                <el-select
                    v-model="condition.parentId"
                    clearable
                    placeholder="请选择父分类"
                    style="width: 150px; float: right; margin: 8px;"
                    @change="selectByPage(1)"
                >
                  <el-option label="所有父分类-----" value="0" />
                  <el-option
                      v-for="(parent,index) in allParentList"
                      :key="index"
                      :label="parent.name"
                      :value="parent.id"
                  />
                </el-select>
                <!--上架下架筛选器-->
                <el-select
                    v-model="condition.status"
                    clearable
                    placeholder="请选择是否上架"
                    style="width: 150px; float: right; margin: 8px;"
                    @change="selectByPage(1)"
                >
                  <el-option label="上架" value="1" />
                  <el-option label="下架" value="0" />
                </el-select>
                <el-input v-model="condition.name" style="width: 240px; float: right; margin: 8px;" placeholder="输入分类名称搜索"
                          :prefix-icon="Search" @input="selectByPage(1)" />
                <el-table :data="categoryList" style="width: 100%; " border>
                    <el-table-column prop="id" label="ID" width="80" />
                    <el-table-column prop="name" label="分类名称" width="180" />
                    <el-table-column prop="dscp" label="分类描述" />
                    <el-table-column label="图片" width="80">
                      <template #default="scope">
                        <el-avatar shape="square" :size="50"
                                   :src="SERVER_ADDR + '/category/pic/' + scope.row.pic"
                                   :title="SERVER_ADDR + '/category/pic/' + scope.row.pic"
                        />
                      </template>
                    </el-table-column>
                  <el-table-column label="所属分类">
                    <template #default="scope">
                      <el-text class="mx-1" type="primary" v-if="scope.row.parent">
                        {{scope.row.parent.name}}
                      </el-text>
                    </template>
                  </el-table-column>
                  <el-table-column prop="recom" label="是否推荐">
                    <template #default="scope">
                      <el-switch
                          :active-value="1" :inactive-value="0" size="large "
                          active-text="推荐" inactive-text="不推荐" inline-prompt
                          v-model="scope.row.recom" class="ml-2"
                          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                          @change="updateRecom(scope.row.id, scope.row.recom)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="是否上架">
                    <template #default="scope">
                      <el-switch
                          :active-value="1" :inactive-value="0" size="large"
                          active-text="上架" inactive-text="下架" inline-prompt
                          v-model="scope.row.status" class="ml-2"
                          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                          @change="updateStatus(scope.row.id, scope.row.status)"
                      />
                    </template>
                  </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button size="small" type="primary" @click="selectById(scope.row.id)">
                                修改
                            </el-button>
                            <!-- 删除的气泡框 -->
                            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
                                icon-color="#626AEF" title="确定要删除吗?" @confirm="del(scope.row.id)"
                                @cancel="cancelEvent">
                                <template #reference>
                                    <el-button size="small" type="danger">
                                        删除
                                    </el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-row class="row-bg" justify="center">
                  <el-pagination background layout="prev, pager, next" :page-count="pageInfo.pages"
                                 style="margin: 10px;" page-size=5 small="true" v-model:current-page="pageInfo.pageNum"
                                 @update:current-page="selectByPage" />
                </el-row>
            </el-card>
        </el-col>
    </el-row>
    <!-- end表单主体部分 -->

    <!-- start增加提示框 -->
    <div>
        <el-dialog v-model="AddShowFlag" title="添加分类" width="500">
            <el-form :rules="rules" ref="ruleFormRef" :model="categoryAdd">
              <el-form-item label="名称" label-width="20%" prop="name">
                  <el-input autocomplete="off" v-model="categoryAdd.name" />
              </el-form-item>
              <el-form-item label="描述" label-width="20%" prop="dscp">
                  <el-input autocomplete="off" v-model="categoryAdd.dscp" />
              </el-form-item>
              <el-form-item label="图片" label-width="20%" prop="pic">
                <el-upload class="avatar-uploader" :action="SERVER_ADDR + '/category/upload'" name="pic"
                           :headers="headers"
                           :show-file-list="false"
                           :before-upload="beforeAvatarUpload"
                           :on-success="handleUploadAdd"
                >
                  <img v-if="categoryAdd.pic" :src="SERVER_ADDR + '/category/pic/' + categoryAdd.pic" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
              <!--写成for渲染的下拉列表-->
              <el-form-item label="父分类" label-width="20%" prop="parentId">
                <el-select v-model="categoryAdd.parentId" placeholder="请选择父分类" clearable :empty-values="[0]" :value-on-clear="0">
                  <el-option v-for="(parent, index) in allParentList" :key="index" :label="parent.name"
                             :value="parent.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="是否推荐" label-width="20%" prop="recom">
                <el-radio-group v-model="categoryAdd.recom" style="margin-left: 8px;">
                  <el-radio value="0">不推荐</el-radio>
                  <el-radio value="1">推荐</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否上架" label-width="20%" prop="status">
                <el-radio-group v-model="categoryAdd.status" style="margin-left: 8px;">
                  <el-radio value="0">未上架</el-radio>
                  <el-radio value="1">上架</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="AddShowFlag = false">取消</el-button>
                    <el-button type="primary" @click="insert()">
                        保存
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
    <!-- end增加提示框 -->

    <!-- start修改提示框 -->
    <div>
      <el-dialog v-model="UpdateShowFlag" title="修改分类" width="500">
        <el-form :rules="rules" ref="ruleFormRef" :model="categoryUpdate">
          <el-form-item label="名称" label-width="20%" prop="name">
            <el-input autocomplete="off" v-model="categoryUpdate.name" />
          </el-form-item>
          <el-form-item label="描述" label-width="20%" prop="dscp">
            <el-input autocomplete="off" v-model="categoryUpdate.dscp" />
          </el-form-item>
          <el-form-item label="图片" label-width="20%" prop="pic">
            <el-upload class="avatar-uploader" :action="SERVER_ADDR + '/category/upload'" name="pic"
                       :headers="headers"
                       :show-file-list="false"
                       :before-upload="beforeAvatarUploadUpdate"
                       :on-success="handleUploadUpdate"
            >
              <img v-if="categoryUpdate.pic" :src="SERVER_ADDR + '/category/pic/' + categoryUpdate.pic" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <!--写成for渲染的下拉列表-->
          <el-form-item label="父分类" label-width="20%" prop="parentId">
            <el-select v-model="categoryUpdate.parentId" placeholder="请选择父分类" clearable :empty-values="[0]" :value-on-clear="0">
              <el-option v-for="(parent, index) in allParentList" :key="index" :label="parent.name"
                         :value="parent.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否推荐" label-width="20%" prop="recom">
            <el-radio-group v-model="categoryUpdate.recom" style="margin-left: 8px;">
              <el-radio :value="0">不推荐</el-radio>
              <el-radio :value="1">推荐</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否上架" label-width="20%" prop="status">
            <el-radio-group v-model="categoryUpdate.status" style="margin-left: 8px;">
              <el-radio :value="0">未上架</el-radio>
              <el-radio :value="1">上架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="UpdateShowFlag = false">取消</el-button>
            <el-button type="primary" @click="update(categoryUpdate)">
              保存
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- end编辑提示框 -->
</template>

<script setup>
import categoryApi from '@/api/CategoryApi.js';
import {computed, ref} from 'vue';
import { ElMessage } from 'element-plus';
import { useTokenStore } from '@/stores/token';
//导出元素
const tokenStore = useTokenStore();
//解决token跟头像上传冲突，设置请求头
const headers = computed(() => {
  const token = tokenStore.tokenStr;
  return {
    token: token
  }
});
//父分类
const allParentList = ref([]);
//查询所有父分类
function selectAllParent() {
    categoryApi.selectAllParent().then(resp => {
        console.log(resp);
        allParentList.value = resp.data;
    })
}
selectAllParent();

//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
//分页查询分类信息
const categoryList = ref([]);
//分页信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0
});
const condition = ref({
  name: null,
  parentId: null,
  status: null
})
function selectByPage(pageNum) {
  categoryApi.selectByPage(condition.value,pageNum,5)
      .then(resp => {
        if (resp.code === 10000) {
          console.log(resp);
          categoryList.value = resp.data.list;
          pageInfo.value = resp.data;
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 1200,
            onClose: () => {
              // oage.value = '';
            }
          });
        }
      });
}
selectByPage(1);


//显示增加对话框
const AddShowFlag = ref(false);
//新增社区信息
const categoryAdd = ref(
    {
      name: null,
      dscp: null,
      pic: null,
      parentId: 0,
      recom: '1',
      status: '1'
    }
)
//保存增加信息
function insert() {
    ruleFormRef.value.validate((valid) => {
        if (valid) {
            categoryApi.insert(categoryAdd.value)
                .then(resp => {
                    if (resp.code == 10000) {
                        ElMessage({
                            message: resp.msg,
                            type: 'success',
                            duration: 1200
                        });
                        AddShowFlag.value = false;
                        categoryAdd.value = {
                          name: null,
                          dscp: null,
                          pic: null,
                          parentId: 0,
                          recom: 1,
                          status: 1
                        }
                        selectByPage(1);
                    } else {
                        ElMessage({
                            message: resp.msg,
                            type: 'danger',
                            duration: 2000
                        });
                    }
                });
        } else {
            ElMessage.error('提交失败,请检查输入内容!')
            return false
        }
    })
}



const cancelEvent = () => {
}
//删除部门数据
function del(id) {
    categoryApi.delete(id)
        .then(resp => {
            if (resp.code == 10000) {
                ElMessage({
                    message: resp.msg,
                    type: 'success',
                    duration: 1200
                });
                selectByPage(pageInfo.value.pageNum);
            } else {
                ElMessage({
                    message: resp.msg,
                    type: 'danger',
                    duration: 2000
                });
            }
        })
}


//显示编辑的提示框
const UpdateShowFlag = ref(false);
//被编辑部门的信息
const categoryUpdate = ref(
    {
      id: null,
      name: null,
      dscp: null,
      pic: null,
      parentId: 0,
      recom: '1',
      status: '1'
    }
)
//编辑部门信息
//回显数据
function selectById(id) {
    UpdateShowFlag.value = true;
    categoryApi.selectById(id)
        .then(resp => {
            if (resp.code == 10000) {
                categoryUpdate.value = resp.data;
            }
        });
}
//保存更新数据
function update(categoryUpdate) {
    ruleFormRef.value.validate((valid) => {
        if (valid) {
            categoryApi.update(categoryUpdate)
                .then(resp => {
                    if (resp.code == 10000) {
                        ElMessage({
                            message: resp.msg,
                            type: 'success',
                            duration: 1200
                        });
                        UpdateShowFlag.value = false;
                        selectByPage(pageInfo.value.pageNum);
                    } else {
                        ElMessage({
                            message: resp.msg,
                            type: 'danger',
                            duration: 2000
                        });
                    }
                });
        } else {
            ElMessage.error('提交失败，请检查输入内容!')
            return false
        }
    })
}
//修改的图片上传
function beforeAvatarUploadUpdate(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('头像仅支持jpg格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true;
}
//图片上传
function beforeAvatarUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('头像仅支持jpg格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true;
}

//增加的上传请求
function handleUploadAdd(resp){
  if (resp.code === 10000){
    ElMessage.success(resp.msg);
    categoryAdd.value.pic = resp.data;
  }else {
    ElMessage.error(resp.msg)
  }
}
//修改的上传请求
function handleUploadUpdate(resp){
  if (resp.code === 10000){
    ElMessage.success(resp.msg);
    categoryUpdate.value.pic = resp.data;
  }else {
    ElMessage.error(resp.msg)
  }
}

//表单验证
const rules = {
    name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  dscp: [{ required: true, message: '请输入商品描述', trigger: 'blur' }]
}
const ruleFormRef = ref(null);
//定义方法修改状态
function updateRecom(id, recom) {
  const updateRecomForm = {
    id,
    recom
  }
  categoryApi.update(updateRecomForm)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage.error(resp.msg);
        }
      })
}
function updateStatus(id, status) {
  const updateStatusForm = {
    id,
    status
  }
  categoryApi.update(updateStatusForm)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage.error(resp.msg);
        }
      })
}
</script>

<style scoped>
/* 图片上传格式 */
.avatar-uploader,
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #060f1c;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>